import {createRouter, createWebHistory} from "vue-router";
import type { RouteLocationNormalized, RouteLocationNormalizedLoaded,NavigationGuardNext} from "vue-router";
import NProgress from "nprogress";
import useAdmin from "@/store/modules/admin.ts";
import store from "@/store";
import type {TRoute} from "@/api/admin/type.ts";
const modules = import.meta.glob("../views/**/*.vue");
const adminStore = useAdmin(store);
const router = createRouter({
    history:createWebHistory(),
    routes:[
        {
            // 主界面
            path:"/",
            name:"index",
            meta:{
                // 需要验证是否登陆过
                isAuth:true
            },
            component:()=>import("@/views/Index/index.vue"),
        },
        {
            // 登陆
            path:"/login",
            name:"login",
            component:()=>import("@/views/Login/index.vue"),
        },
        {
            path:"/:pathMath(.*)*",
            name:"noFound",
            // path:"*",
            component:()=>import("@/views/NoFound/index.vue"),
        }
    ]
});
// 路由守卫
router.beforeEach(async function(to:RouteLocationNormalized,_:RouteLocationNormalizedLoaded,next:NavigationGuardNext){
    NProgress.start();// 启动进度条
    // 判断路由是否需要验证权限
    if(to.meta.isAuth){
        // 判断有没有token,如果没有token说明没有访问的权限，需要跳转至登陆界面
        if(adminStore.token){
            // 判断是否获取了个人信息，如果未获取个人信息，重新获取一次即顶号
            if(!adminStore.info)
                await adminStore.getAdminInfoAsync();// 获取个人信息
            next();
        }else{
            next({
                path:"/login",
                query:{
                    returnUrl:to.path
                }
            })
        }
    }else{
        next();
    }
})
router.afterEach(function(){
    NProgress.done();// 结束进度
})
// 异步设置路由
export const setRoute = function(routeList:TRoute[],parentName:string){
    routeList.forEach(item=>{
        const arr = item.componentPath.split("/");
        const name = arr[arr.length-1];// 获取路由的名字
        // 判断当前路由信息表中是否存在该路由,并且路由的name不允许为undefined
        if(!name || router.hasRoute(name)) return;
        // 添加二级路由
        router.addRoute(parentName,{
            path:item.routePath,
            name,
            component:modules["../views"+item.componentPath+"/index.vue"]
        });

        if(item.children && item.children.length>0)
            setRoute(item.children,name);
    })
}
export default router;